package com.zbkj.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zbkj.client.service.DialogMemberService;
import com.zbkj.client.service.DialogService;
import com.zbkj.client.service.MessageService;
import com.zbkj.common.request.client.SendMessageRequest;
import com.zbkj.common.response.client.DialogListResponse;
import com.zbkj.common.response.client.MessageList;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.model.client.message.Dialog;
import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.client.config.WebSocketSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class MessageWebSocketHandler extends TextWebSocketHandler {
    @Autowired
    private DialogService dialogService;
    @Autowired
    private DialogMemberService dialogMemberService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ClientTokenComponent clientTokenComponent;
    @Autowired
    private WebSocketSessionManager webSocketSessionManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从会话属性中获取token
        String token = (String) session.getAttributes().get("token");
        if (token == null || token.trim().isEmpty()) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("event", "unauthorized");

            session.sendMessage(new TextMessage(JSON.toJSONString(hashMap)));

            session.close();
            return;
        }
        
        // 验证token并获取用户ID
        Integer userId = clientTokenComponent.getUserIdByToken(token);
        if (userId == null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("event", "unauthorized");

            session.sendMessage(new TextMessage(JSON.toJSONString(hashMap)));

            session.close();
            return;
        }

        // 注册用户会话到管理器
//        webSocketSessionManager.registerSession(userId, session);
        try {
            // 将用户ID保存到会话属性中，供后续消息处理使用
            session.getAttributes().put("userId", userId);
            webSocketSessionManager.registerSession(userId, session);
        } catch (Exception e) {
            log.error("注册WebSocket会话失败，userId={}, sessionId={}", userId, session.getId(), e);
            // 可以选择关闭session，也可以让其继续
            session.close();
        }
        session.sendMessage(new TextMessage("WebSocket连接成功，用户ID: " + userId));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 从会话属性中获取用户ID
        Integer userId = (Integer) session.getAttributes().get("userId");
        String token =  (String) session.getAttributes().get("token");

        if (userId == null) {
            session.sendMessage( new TextMessage("{\"event\":\"unauthorized\",\"data\":\"未登录\"}"));
            return;
        }
        
        String payload = message.getPayload();
        JSONObject json = JSON.parseObject(payload);
        String action = json.getString("action");
        JSONObject data = json.getJSONObject("data");
        
        switch (action) {
            case "ping":
                // 刷新WebSocket连接的活跃时间
                webSocketSessionManager.refreshSocket(session);
                session.sendMessage(new TextMessage("pong"));
                break;
            case "sendMessage":
                SendMessageRequest sendReq = data.toJavaObject(SendMessageRequest.class);
                // 传递session参数，由service层流式推送
                messageService.sendMessageWebSocket(sendReq, userId, token, session);
                break;

            case "getMessageList":
                Integer dialogId = data.getInteger("dialogId");
                Integer page = data.getInteger("page");
                Integer pagesize = data.getInteger("pagesize");
                List<MessageList> msgList = messageService.getMessageList(dialogId, page, pagesize);
                session.sendMessage(new TextMessage(JSON.toJSONString(msgList)));
                break;

            case "getDialogList":
                // 使用从会话中获取的userId，而不是从data中获取
                List<DialogListResponse> dialogList = dialogService.getDialogList(userId);
                session.sendMessage(new TextMessage(JSON.toJSONString(dialogList)));
                break;
            case "delDialog":
                Integer dialogIdDel = data.getInteger("dialogId");
                Dialog dialog = dialogService.getById(dialogIdDel);
                if (dialog != null) {
                    dialogService.removeById(dialogIdDel);
                }
                Map<String, Object> delData = new HashMap<>();
                delData.put("result", 1);
                session.sendMessage(new TextMessage(JSON.toJSONString(delData)));
                break;
            case "testStream":
                int fileNumber = (int) (Math.random() * 10) + 1;
                String fileName = "text/text" + fileNumber + ".txt";
                try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName)) {
                    if (inputStream != null) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            String chunk = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
                            session.sendMessage(new TextMessage(chunk));
                            Thread.sleep(100);
                        }
                    } else {
                        session.sendMessage(new TextMessage("文本文件未找到"));
                    }
                } catch (Exception e) {
                    session.sendMessage(new TextMessage("读取文件时发生错误: " + e.getMessage()));
                }
                break;
            default:
                session.sendMessage(new TextMessage("未知操作"));
        }
    }
    
    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        // 从会话属性中获取用户ID
        Integer userId = (Integer) session.getAttributes().get("userId");
        if (userId != null) {
            // 从会话管理器中移除指定的用户会话
            webSocketSessionManager.removeSession(userId, session);
            log.info("用户 {} 的WebSocket连接已关闭，会话ID: {}", userId, session.getId());
        }
    }
} 